package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.JsonUtil;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBoardService boardService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${forum.redis-article-rankList-key}")
    private String rankListKey;
    @Value("${forum.redis-hotArticle-key}")
    private String hotArtKey;
    @Value("${forum.article-hot-likeCount}")
    private int hotCount;
    @Value("${forum.redis-upvoteList-key}")
    private String upvoteKey;


    @Override
    public void create(Article article) {
        if(article == null || article.getUserId() == null ||
                            article.getBoardId() == null ||
                            StringUtil.isEmpty(article.getTitle()) ||
                            StringUtil.isEmpty(article.getContent())) {

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //  1. 帖子表新增
        //  1.1 为了减轻数据库的负担，在业务中给文章 赋默认值
        article.setVisitCount(0);// 访问数
        article.setReplyCount(0);// 回复数
        article.setLikeCount(0);//  点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //  1.2 插入数据库
        int artRow = articleMapper.insertSelective(article);
        if(artRow != 1) {
            log.warn(ResultCode.FAILED_CREATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //  2. 用户表更新
        User user = userService.selectById(article.getUserId());
        if(user == null) {
            log.warn(ResultCode.FAILED_CREATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        userService.addOneArticleCountById(user.getId());

        //  3. 板块表更新
        Board board = boardService.selectById(article.getBoardId());
        if(board == null) {
            log.warn(ResultCode.FAILED_CREATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        boardService.addOneArticleCountById(board.getId());

        //  4. 打印成功日志
        log.info(ResultCode.SUCCESS.getMessage() + "发帖成功:" +
                " articleId = " + article.getId() +
                " userId = " + article.getUserId() +
                " boardId = " + article.getBoardId());

    }

    @Override
    public List<Article> selectList() {
        List<Article> articles = articleMapper.selectList();
        return articles;
    }

    @Override
    public List<Article> selectList(Long boardId) {
        if(boardId == null || boardId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //  校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        List<Article> articles = articleMapper.selectList(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        //  查询文章详情
        Article article = articleMapper.selectDetailById(id);
        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS.getMessage());
        }

        //  让文章浏览量 +1
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(ResultCode.FAILED.getMessage());
        }

        return article;
    }

    @Override
    public Article selectById(Long id) {
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Article> selectAllByUserId(Long userId) {
        if(userId == null || userId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        User user = userService.selectById(userId);
        if(user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
        }
        //  调用mapper
        List<Article> articles = articleMapper.selectAllByUserId(userId);
        return articles;
    }

    @Override
    public void modify(Long id,String title,String content) {
        //  1. 参数校验
        if(id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }

        //  2. 给新文章赋默认值
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        article.setUpdateTime(new Date());

        //  3. 调用mapper
        int row = articleMapper.updateByPrimaryKeySelective(article);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(ResultCode.FAILED.getMessage());
        }
    }

    @Override
    public void upvote(Long articleId,Long userId) {
        if(articleId == null || userId == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        //  1. 判断文章状态
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if(article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS.getMessage());
        }
        if(article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_BANNED.getMessage());
        }

        //  判断点赞是否有效
        String curUpvoteKey = upvoteKey + article.getId();
        String curUpvoteVal = String.valueOf(userId);
        //  保存到点赞总列表
        Long add = redisTemplate.opsForSet().add(curUpvoteKey, curUpvoteVal);
        if(add == null || add == 0) {
            //  已经点过赞了
            return;
        }

        //  2. 重新组装数据
        //  2.1 为了让读写更快，重新定义一个对象
        Article updateArticle = new Article();
        updateArticle.setId(articleId);
        int newCount = article.getLikeCount() + 1;
        updateArticle.setLikeCount(newCount);
        updateArticle.setUpdateTime(new Date());

        //  3. 保存到 Redis 中
        //  保存到文章点赞数
        redisTemplate.opsForZSet().add(rankListKey,article.getId().toString(),newCount);
        //  判断是否是点数据，如果是，存入Redis
        if(newCount > hotCount) {
            String artJson = JsonUtil.toJson(article);
            String artId = String.valueOf(article.getId());
            redisTemplate.opsForHash().putIfAbsent(hotArtKey,artId,artJson);
        }

        //  4. 调用mapper
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.FAILED + ". 更新数据库失败");
            throw new ApplicationException(ResultCode.FAILED.getMessage());
        }
    }

    @Override
    public void deleteById(Long id) {
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        //  1. 检验文章状态
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS.getMessage());
        }
        if(article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_BANNED.getMessage());
        }
        //  2. 重新组装数据
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);

        //  3. 调用mapper
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.FAILED.toString() + ". 删除操作失败");
            throw new ApplicationException(ResultCode.FAILED.getMessage());
        }

        //  4. 用户文章数 - 1
        userService.subOneArticleCountById(article.getUserId());

        //  5. 板块文章数 - 1
        boardService.subOneArticleCountById(article.getBoardId());
        log.info("删除帖子成功. article.id = " + article.getId() +
                " user.id = " + article.getUserId() +
                " board.id = " + article.getBoardId());
    }

    @Override
    public List<Article> searchForContent(String text) {
        //  直接调用mapper即可
        List<Article> articles = articleMapper.searchForContent(text);
        return  articles;
    }

    @Override
    public List<Object> getHot() {

        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        Set<String> typedTuple =
                redisTemplate.opsForZSet().reverseRange(rankListKey, 0, -1);
        List<Object> articles = hashOps.multiGet(hotArtKey,typedTuple);
        System.out.println(articles);
        return articles;
    }
}
